<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Models\Admin;
use App\Services\SmsService;
use Dingo\Api\Http\Request;

class AuthController extends BaseController
{
    public function login(Request $request)
    {
        $input = $request->only(['username', 'password']);
        $this->validate($request, [
            'username'   => 'required',
            'password'  => 'required',
        ], [
            'username.required' => '用户名为空',
            'password.required' => '密码为空'
        ]);
        if (! $token = auth('admin')->attempt($input)) {
            return $this->failed("用户名或者密码错误");
        }
        return $this->respondWithToken($token);
    }

    public function permission(Request $request) {
        $user = $this->getUser();
        return $this->success(compact('user'));
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return $this->success(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    public function smsLogin(Request $request) {
        $this->validate($request, [
            'phone' => 'regex:/^1[345789][0-9]{9}$/',
            'code' => 'required'
        ]);
        $is_valid = SmsService::validYzm(\request('phone'), \request('code'));
        if (!$is_valid)
            return $this->failed("code无效");

        $user = Admin::where('phone', \request('phone'))->first();
        if (!$user)
            return $this->failed("手机号无效");

        auth('admin')->login($user);
        if (! $token = auth('admin')->fromUser($user)) {
            return $this->failed("Unauthorized", 401);
        }
        return $this->respondWithToken($token);
    }

    public function sendCode(Request $request) {
        $this->validate($request, [
            'phone' => 'regex:/^1[345789][0-9]{9}$/',
        ]);
        $code = SmsService::sendYzm(\request('phone'));
        if (env('RETURN_CODE_DEBUG', false)) {
            return $this->success([
                'code' => $code
            ], '发送成功');
        }
        return $this->success([], '发送成功');
    }


}
